const Service = require('egg').Service;

class ListService extends Service {
    async getList() {
        const {ctx,app} = this;// ctx上下文 app跟实例有且只有一个
        // 分页  搜索呀 模糊查询  排序
        const {pageIndex,pageSize, keyword, sortBy,sortType,id}  =ctx.query;
        let sql = `select * from blogs where 1=1 `;
        let sqlCount = `select count(id) as total from blogs where 1=1 `
        if(keyword) {
            sql+= `and title like "%${keyword}%" `
            sqlCount+= `and title like "%${keyword}%" `
        }
        if(id) {
            sql+= `and id=${id} `
            sqlCount+= `and id=${id} `
        }
        if(sortBy && sortType) {
            sql += `order by ${sortBy} ${sortType} `
        }
        if(pageIndex && pageSize) {
            sql += `limit ${(pageIndex-1)*pageSize},${pageSize}`
        }
        const data = await app.mysql.query(sql)
        const [{total}] = await app.mysql.query(sqlCount)
        return {
            data,
            total
        }
    }
    async addList() {
        const {ctx,app} = this;
        const data = await app.mysql.insert('blogs', {...ctx.request.body, create_time:Date.now()})
        return data;
    }
    async editList() {
        const {ctx,app} = this;
        const data = await app.mysql.update('blogs', {...ctx.request.body})
        return data;
    }
    async delList() {
        const {ctx,app} = this;
        const {id} = ctx.params;
        const data = await app.mysql.delete('blogs', {id})
        return data;
    }
}

module.exports = ListService;
